package pl.enigmatic.parser.string.custom;

import pl.enigmatic.parser.string.Converter;


/**
 * Converter to convert human-readable time values into their representation in seconds. The String time representation is as follows:
 * dd:hh:MM:ss where all of these values can be any arbitrary double values, and represent days, hours, minutes and seconds. The days value, although
 * possible, will rarely be necessary, so we will omit it later on. The seconds are count with the following equation then: <br/>
 * <strong>milliseconds=ss + (60 * (MM + 60 * (hh + 24*dd)))</strong> <br/>
 * So, for instance, the following example values will be fine: 0:1:12, 0:0:66, 0:1.4:234.6. To ease xml readability writing values like ::14, :12: or
 * even just 14 or 12: is also permitted.
 * 
 * @author reggie_7
 */
public class TimeSecondsDoubleConverter extends Converter<Double> {

	private final static int[] factors = { 1, 60, 60 * 60, 24 * 60 * 60 };

	@Override
	public Double convert(final String value) {
		final String[] split = ("0" + value.replace(":", ":0")).split(":");
		double res = 0;
		for (int i = 0; i < split.length && i < factors.length; i++) {
			res += factors[i] * Double.parseDouble(split[split.length - i - 1]);
		}
		return res;
	}

	@Override
	public String convertBack(final Double value) {
		long div = (long) Math.floor(value / 1000);
		final double rem = value / 1000 - div;
		String res = "";
		for (int i = factors.length - 1; i >= 1; i--) {
			if (div >= factors[i]) {
				res += div / factors[i] + ":";
			}
			div = div % factors[i];
		}
		return res + (div + rem);
	}
}
